package com.neuqsoft.rd.citizen.thirdapp.sdk;

import cn.hutool.core.util.URLUtil;
import com.neuqsoft.rd.citizen.thirdapp.demo.DemoConstant;
import com.neuqsoft.rd.citizen.thirdapp.demo.dto.UserLoginDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author baidh
 * @date 2020/12/02
 */
@Service
public class OAuthService {

    public static final String REDIRECT_URI = URLUtil.encode("https://service.neuqsoft.com/ggfw/citizen/demo/api/scene3/token");
//    public static final String REDIRECT_URI = URLUtil.encode("http://10.19.92.212:8080/api/scene3/token");

    private static final String URL = "https://service.neuqsoft.com/ggfw/citizen/rest/auth/oauth/token?grant_type=authorization_code&client_id="
            + DemoConstant.APPID + "&client_secret=" + DemoConstant.APPSECRET + "&redirect_uri={redirectUri}&code={code}";

    @Autowired
    RestTemplate restTemplate;

    /**
     * 授权码解析
     *
     * @param code
     * @param redirectUri
     * @return
     */
    public UserLoginDTO oauthToken(String code, String redirectUri) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("code", code);
        if (StringUtils.isEmpty(redirectUri)) {
            paramMap.put("redirectUri", REDIRECT_URI);
        } else {
            paramMap.put("redirectUri", URLUtil.encode(redirectUri));
        }
        return restTemplate.postForEntity(URL, null, UserLoginDTO.class, paramMap).getBody();
    }
}
